package com.xiaren.util;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Created by xiaren on 2017/4/5.
 * @主页 http://www.leaf123.cn/
 * @邮箱 xia5523@qq.com
 */
public class FileChooserUtil {


    public static String saveImage(Image image, String defaultFileName) {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);//只能选择文件
        fc.setFileFilter(new FileNameExtensionFilter("图片", new String[]{".png"}));
        fc.setSelectedFile(new File(defaultFileName));
        String path = null;
        File f = null;
        Integer flag = 0;
        try {
//            flag=fc.showOpenDialog(null);
            flag = fc.showSaveDialog(fc);
        } catch (HeadlessException head) {
            System.out.println("Open File Dialog ERROR!");
        }
        if (flag == JFileChooser.APPROVE_OPTION) {
            //获得该文件
            f = fc.getSelectedFile();
            if (!f.getPath().endsWith(".png")) {
                path = f.getPath() + ".png";
            }
        }
        BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();

        boolean b = g2d.drawImage(image, 0, 0, null, null);
        g2d.dispose();
        try {
            System.out.println(path);
            ImageIO.write(bi, "png", new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    public static String exportFile(String content, String defaultFileName) {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);//只能选择文件
        fc.setFileFilter(new FileNameExtensionFilter("文本", new String[]{".txt"}));
        fc.setSelectedFile(new File(defaultFileName));
        String path = null;
        File f = null;
        Integer flag = 0;
        try {
            flag = fc.showSaveDialog(fc);
        } catch (HeadlessException head) {
            System.out.println("Open File Dialog ERROR!");
        }
        if (flag == JFileChooser.APPROVE_OPTION) {
            //获得该文件
            f = fc.getSelectedFile();
            if (!f.getPath().endsWith(".txt")) {
                path = f.getPath() + ".txt";
            }
        }


        FileOutputStream fos;
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        pw.write(content);
        pw.flush();
        pw.close();
        return path;
    }


}
